<template>
	<view class="upload_image">
		<view class="list_box" :class="onePicClass" :style="{ minHeight: height + 'rpx'}">
			<view class="item" v-for="(item, index) in imgList" :key="index"
				:style="{ width: width + 'rpx', height: height + 'rpx'}">
				<image class="img_pre" :src="item" mode="aspectFit"
					:style="{ width: width + 'rpx', height: height + 'rpx'}" @click="imgPre(item)"></image>
				<!-- <view class="del_btn" @click="delImg(index)">
					<view class="del_icon_wrap">
						<image class="del_icon" src="../static/images/del.png"></image>
					</view>
				</view> -->
			</view>
			<view class="add_btn" :class="addBtnClass" @click="addImg" v-if="imgList.length < maxCount">
				<view class="icon icon_camera" :style="{ width: width + 'rpx', height: height + 'rpx'}">
					<image class="camera_icon" src="../static/images/camera.png"></image>
				</view>
			</view>
		</view>
		<view class="canvas_view">
			<canvas id="firstCanvas" class="firstCanvas" canvas-id="firstCanvas"
				:style="{width: canvasWidth+'px', height: canvasHeight+'px'}"></canvas>
		</view>
	</view>
</template>

<script>
	export default {
		props: {
			maxCount: { // 最大上传数量
				type: Number,
				default: 1
			},
			iconType: { // 图标类型 camera plus
				type: String,
				default: 'camera'
			},
			sourceType: { // album 从相册选图，camera 使用相机
				type: Array,
				default: () => ['album', 'camera']
			},
			width: { //	宽 单位rpx
				type: Number,
				default: 90
			},
			height: { // 高 单位rpx
				type: Number,
				default: 90
			},
			maxSize: { // 图片最大大小
				type: Number,
				default: 8
			},
			sizeType: {
				type: Array,
				default: () => ['compressed']
			},
			quality: {
				type: Number,
				default: 0.6
			},
		},
		data() {
			return {
				imgList: [], // 图片列表
				uploadUrl: '', // 上传图片的服务器请求地址
				visiable: false, // 显示组件的标识
				context: undefined, // canvas 绘图上下文
				canvasWidth: 0, // 默认宽度 100px、高度 100px
				canvasHeight: 0,
			};
		},
		mounted() {
			this.context = uni.createCanvasContext('firstCanvas', this);
		},
		computed: {
			onePicClass() {
				return this.maxCount === 1 ? "one_pic" : "multi_pic";
			},
			addBtnClass() {
				return this.imgList.length != 0 && this.maxCount != 1 ? "add_margin" : ""
			}
		},
		methods: {
			imgPre(url) {
				//图片预览
				wx.previewImage({
					current: url, // 当前显示图片的http链接
					urls: this.imgList // 需要预览的图片http链接列表
				})
			},
			// 删除图片
			delImg(index) {
				uni.showModal({
					title: '',
					content: '确认删除当前图片？',
					success: (res) => {
						if (res.confirm) {
							this.imgList.splice(index, 1);
							this.$emit('imgListChange', this.imgList);
							uni.showToast({
								title: '删除成功！'
							});
						}
					}
				});
			},

			// 添加图片
			addImg() {
				// 从本地相册选择图片或使用相机拍照
				uni.chooseImage({
					count: 1,
					sourceType: this.sourceType, //从相册选择
					// sizeType: this.sizeType,
					success: (res) => {
						const tempFilePaths = res.tempFilePaths;
						const tempFiles = res.tempFiles[0];
						if (parseInt(tempFiles.size) > this.maxSize * 1024 * 1024) {
							uni.showToast({
								title: '图片过大，请确保上传图片小于8MB',
								icon: 'none'
							})
						} else {
							this.compressImg(tempFilePaths, [], 0);
							// this.uploadImg(tempFilePaths, 0);
						}
					},
					fail(err) {
						console.log(err)
					}
				});
			},

			// 压缩图片
			compressImg(tempFilePaths, compressPaths, index) {
				uni.showLoading({
					title: '图片上传中',
					mask: true
				});
				let i = index;
				let arr = [...compressPaths];
				uni.getImageInfo({
					src: tempFilePaths[i],
					success: (res) => {
						if (res) {
							let canvasWidth = res.width // 图片原始长宽
							let canvasHeight = res.height;

							this.canvasWidth = canvasWidth;
							this.canvasHeight = canvasHeight;

							// canvas宽高重新设置后会有一段渲染的间隔，这个间隔可能导致画到画布的图片出现大小不一致的bug，这里做下300ms延迟处理兼容
							setTimeout(() => {
								this.context.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
								this.context.drawImage(res.path, 0, 0, this.canvasWidth, this
									.canvasHeight);
								this.context.draw(false, () => {
									// 将图片画到canvas上面，使用Canvas压缩
									uni.canvasToTempFilePath({
										x: 0,
										y: 0,
										width: this.canvasWidth,
										height: this.canvasHeight,
										destWidth: this.canvasWidth,
										destHeight: this.canvasHeight,
										canvasId: 'firstCanvas',
										fileType: 'jpg',
										quality: this.quality,
										success: (res) => {
											// 在H5平台下，tempFilePath 为 base64
											i++;
											arr.push(res.tempFilePath);
											this.urlTobase64(res.tempFilePath)
											console.log(res.tempFilePath)
											if (i < tempFilePaths.length) {
												this.compressImg(tempFilePaths,
													arr, i);
											} else {
												// 上传服务器
												this.uploadImg(arr, 0);
											}
										},
										fail: (err) => {
											uni.hideLoading();
											uni.showToast({
												title: '网络异常',
												icon: 'none'
											})
										}
									}, this);
								});
							}, 300);
						} else {
							uni.hideLoading();
							uni.showToast({
								title: '网络异常',
								icon: 'none'
							})
						}

					},
					fail: (err) => {
						uni.hideLoading();
						uni.showToast({
							title: '网络异常',
							icon: 'none'
						})
					}
				});

			},
			urlTobase64(url) {
				uni.getFileSystemManager().readFile({
					filePath: url, //选择图片返回的相对路径
					encoding: 'base64', //编码格式
					success: res => { //成功的回调
						let base64 = 'data:image/jpeg;base64,' + res.data //不加上这串字符，在页面无法显示的哦
						// this.dataList.picList.push(base64);
						console.log(base64)

					}
				})
				// this.uploadFile()
			},
			// 上传图片
			uploadImg(tempFilePaths, index) {
				let i = index;

				uni.uploadFile({
					url: `https://test.com/upload`,
					filePath: tempFilePaths[i],
					methods: 'POST',
					name: 'file',
					data: {
						path: tempFilePaths[i]
					},
					success: (res) => {
						uni.hideLoading()
						if (res.data.err) {
							uni.showToast({
								title: '网络异常',
								icon: 'none'
							})
						} else {
							if (res.data) {
								let data = JSON.parse(res.data);
								let url = Object.values(data)
								this.imgList = [...this.imgList, ...url];
								this.$emit('imgListChange', this.imgList);
							}
						}

					},
					fail: (err) => {
						uni.hideLoading()
						uni.showToast({
							title: '网络异常',
							icon: 'none'
						})
					}
				});

			}
		}
	}
</script>

<style scoped lang='scss'>
	.img_pre,
	.item,
	.icon {
		border-radius: 10rpx;
	}

	.item,
	.icon {
		border: 1rpx solid #e5e5e5;
		background-color: #ffffff;
		box-sizing: border-box;
	}

	.item {
		display: flex;
		align-items: center;
		justify-content: center;
		align-items: center;
		position: relative;
		margin: 0 10rpx;
	}

	/* 单照片上传,图片不需要边距 */
	.one_pic {
		.item {
			margin: 0 !important;
		}
	}

	/* 多图会有多行展示的情况,设置上下边距 */
	.multi_pic {

		.item,
		.icon {
			margin-top: 10rpx !important;
			margin-bottom: 10rpx !important;
		}
	}

	/* 多图,并且有上传图片,上传图片按钮要有边距 */
	.add_margin {
		margin: 0 10rpx !important;
	}

	.del_btn {
		position: absolute;
		top: -14rpx;
		right: -14rpx;
		width: 28rpx;
		height: 28rpx;

		.del_icon_wrap {
			width: 28rpx;
			height: 28rpx;
			display: inline-flex;
			align-items: center;
			justify-content: center;
			background-color: red;
			border-radius: 50%;
			position: absolute;

			.del_icon {
				width: 20rpx;
				height: 20rpx;
			}
		}
	}

	.list_box {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: flex-start;
		flex-wrap: wrap;
	}

	.canvas_view {
		opacity: 0;
		position: fixed;
		right: -10000rpx;
		bottom: -10000rpx;
		width: 0rpx;
		height: 0rpx;
		overflow: hidden;
	}

	.icon {
		display: flex;
		align-items: center;
		justify-content: center;

		.camera_icon {
			width: 50rpx;
			height: 37rpx;
		}
	}
</style>
